import { defineStore } from 'pinia'
import { ref } from 'vue'
import { moduleRoutes } from '@/router/index'
import { useRoute, type RouteRecordRaw } from 'vue-router'
import { hasPermission } from '@/utils/common'
import useUserStore from '@/stores/user'

type MenuType = { trigger: boolean } & RouteRecordRaw

const usePermissionStore = defineStore('permission', () => {
  const menuList = ref()
  const route = useRoute()
  const userStore = useUserStore()
  const excludeAliveComponentList = ref<string[]>([]) // 不缓存组件名

  const renderTitles = () => {
    ;(moduleRoutes as MenuType[]).forEach((item) => {
      item.children = item.children
        ?.filter((item) => {
          if (!item.meta?.alive) {
            // 循环中收集 不缓存组件
            excludeAliveComponentList.value.push(item.name as string)
          }
          return item.meta?.menu
        })
        .filter((item) =>
          hasPermission(item.meta?.roles as Array<string>, userStore.userInfo.roles)
        )
      item.trigger = route.path.includes(item.path)
    })
    moduleRoutes.sort((a, b) => (a.meta?.sort as number) - (b.meta?.sort as number))
    menuList.value = moduleRoutes.filter((item) => {
      if (item.children) {
        return item.children.length > 0
      } else {
        return false
      }
    })
  }

  return {
    excludeAliveComponentList,
    menuList,
    renderTitles
  }
})

export default usePermissionStore
